import { defineStore } from 'pinia';
import { reactive, computed } from 'vue';
import arrayToTree from '@/utils/arrayToTree';
import { FuncApi } from "@/api";

export default defineStore('func', () => {
    let isInit: boolean = false;  //初始值
    let allFuncs = reactive<Array<Vm.Func>>([]);  //当前系统的所有功能
    const allFuncstreeData = computed<Array<Vm.FuncNode>>(() => {
        return [{
            func_id: 0, func_name: "ROOT", func_key: "", func_fid: -1,
            children: arrayToTree(allFuncs, "func_id", "func_fid")
        }];
    });
    const init = async () => {
        if(isInit) return;
        allFuncs.push(...await FuncApi.getAll())
        isInit = true;
    }
    const remove = async (func_id: number) => {
        try{
            await FuncApi.remove(func_id);
            await allFuncs.splice(allFuncs.findIndex(item => item.func_id === func_id), 1);
         }catch(e) {/**/}
    };
    const add = async (model: HttpPayload.Func) => {
        const func_id = await FuncApi.add(model);
        await allFuncs.push({ ...model, func_id });
    };
    const update = async (model: HttpPayload.Func) => {
        await FuncApi.update(model);
        await allFuncs.splice(allFuncs.findIndex(item => item.func_id === model.func_id), 1 , { ...model });
    };

    return { allFuncs, allFuncstreeData, remove, add, update, init }
});